package com.starhub.application.collection.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.starhub.application.collection.annotation.CollectionClient;
import com.starhub.application.collection.client.CollectionClientInterface;
import com.starhub.application.collection.enums.CollectionTypeEnums;

import jakarta.annotation.PostConstruct;

import java.util.HashMap;
import java.util.Map;

/**
 * 知识库表客户端
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-06
 */
@Component
public class CollectionComponent {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    private final Map<CollectionTypeEnums, CollectionClientInterface> clientMap = new HashMap<>();
    
    @PostConstruct
    public void init() {
        // 获取所有带有CollectionClient注解的Bean
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(CollectionClient.class);
        
        // 将Bean按照类型放入Map中
        beans.forEach((name, bean) -> {
            if (bean instanceof CollectionClientInterface) {
                CollectionClient annotation = bean.getClass().getAnnotation(CollectionClient.class);
                clientMap.put(annotation.value(), (CollectionClientInterface) bean);
            }
        });
    }
    
    /**
     * 根据类型获取客户端
     * @param type 知识库表类型
     * @return 对应的客户端实现
     */
    public CollectionClientInterface getClient(CollectionTypeEnums type) {
        CollectionClientInterface client = clientMap.get(type);
        if (client == null) {
            throw new IllegalArgumentException("Unsupported collection type: " + type);
        }
        return client;
    }
} 